import {Injectable} from '@nestjs/common';
// ORM
import {InjectRepository} from '@nestjs/typeorm';
import {Repository} from 'typeorm';
import {ApproveEntity} from '../entity/approve.entity';
import {ApproveDto} from '../dto/approve.dto';
import {ApplyStatus, ApproveStatus} from "../common/constants";
import {ApplyDeviceEntity} from "../entity/apply.device.entity";
import {ApplyUserEntity} from "../entity/apply.user.entity";
import {ApplyEntity} from "../entity/apply.entity";

@Injectable()
export class ApproveService {
    constructor(
        @InjectRepository(ApproveEntity)
        private readonly approveRepository: Repository<ApproveEntity>,
    ) {
    }

    async createOne(approveDto: ApproveDto, nextApproveAccountId?: string): Promise<ApproveEntity> {
        let result = null
        try {
            await this.approveRepository.manager.transaction(async (manager) => {
                let status
                if (nextApproveAccountId) {
                    status = ApplyStatus.PENDING
                } else {
                    if (approveDto.status === ApproveStatus.PASSED) {
                        status = ApplyStatus.PASSED
                    }
                    if (approveDto.status === ApproveStatus.REJECTED) {
                        status = ApplyStatus.REJECTED
                    }
                }
                await manager.update(ApplyEntity,{id: approveDto.applyId}, {nextApproveAccountId: nextApproveAccountId || '', status});
                result = await manager.save(ApproveEntity, approveDto);
            });
        } catch(e){
            console.log(e)
        }
        return result
    }

    /**
     * 根据申请id获取审批记录
     * @param applyId
     */
    async getAllByApplyId(applyId: string): Promise<ApproveEntity[]> {
        const qb = this.approveRepository.createQueryBuilder('approve');
        qb.where({applyId})
        qb.innerJoinAndMapOne('approve.deviceInfo', ApplyDeviceEntity, 'device', 'approve.deviceSn = device.deviceSn')
        qb.innerJoinAndMapOne('approve.applyUserInfo', ApplyUserEntity, 'applyUser', 'approve.applyAccountId = applyUser.accountId')
        qb.innerJoinAndMapOne('approve.approveUserInfo', ApplyUserEntity, 'approveUser', 'approve.approveAccountId = approveUser.accountId')
        qb.orderBy({
            "approve.approveTime": "DESC"
        })
        return qb.getMany()
    }

    /**
     * 根据审批人accountId及审批状态分页获取已审批(审批通过|拒绝)列表
     * @param approveAccountId
     * @param status
     * @param pageIndex
     * @param pageSize
     */
    async getPaginationDataByApproveAccountIdAndStatus(approveAccountId: string, status: ApproveStatus, pageIndex: number, pageSize: number): Promise<[ApproveEntity[], number]> {
        const qb = this.approveRepository.createQueryBuilder('approve');
        qb.where({approveAccountId, status})
        qb.innerJoinAndMapOne('approve.deviceInfo', ApplyDeviceEntity, 'device', 'approve.deviceSn = device.deviceSn')
        qb.innerJoinAndMapOne('approve.applyUserInfo', ApplyUserEntity, 'applyUser', 'approve.applyAccountId = applyUser.accountId')
        qb.innerJoinAndMapOne('approve.approveUserInfo', ApplyUserEntity, 'approveUser', 'approve.approveAccountId = approveUser.accountId')
        qb.offset((pageIndex - 1) * pageSize).limit(pageSize)
        return qb.getManyAndCount()
    }

    /**
     * 根据审批人accountId获取所有审批列表
     * @param approveAccountId
     */
    async getAllByApproveAccountId(approveAccountId: string): Promise<ApproveEntity[]> {
        const qb = this.approveRepository.createQueryBuilder('approve');
        qb.where({approveAccountId})
        qb.innerJoinAndMapOne('approve.applyInfo', ApplyEntity, 'apply', 'approve.applyId = apply.id')
        qb.innerJoinAndMapOne('approve.deviceInfo', ApplyDeviceEntity, 'device', 'approve.deviceSn = device.deviceSn')
        qb.innerJoinAndMapOne('approve.applyUserInfo', ApplyUserEntity, 'applyUser', 'approve.applyAccountId = applyUser.accountId')
        qb.innerJoinAndMapOne('approve.approveUserInfo', ApplyUserEntity, 'approveUser', 'approve.approveAccountId = approveUser.accountId')
        qb.orderBy({
            'approve.approveTime': 'DESC'
        })
        return qb.getMany()
    }

}
